package org.hepeng.fabric.gateway.pool.spring.interceptor;

import org.hepeng.fabric.gateway.pool.FabricGatewayKeyHolder;
import org.hepeng.fabric.gateway.pool.GatewayKeyProvider;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author he peng
 * @date 2022/3/24
 */
public class FabricGatewayInterceptor implements AsyncHandlerInterceptor {


    private final GatewayKeyProvider keyProvider;

    public FabricGatewayInterceptor(GatewayKeyProvider keyProvider) {
        this.keyProvider = keyProvider;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        FabricGatewayKeyHolder.set(keyProvider.getKey(request));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        FabricGatewayKeyHolder.remove();
    }
}
